package team.kas.anime.service.serviceImpl;

import it.sauronsoftware.jave.MultimediaInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import team.kas.anime.dao.CollectionMapper;
import team.kas.anime.dao.FanMapper;
import team.kas.anime.dao.UserMapper;
import team.kas.anime.dao.VideoMapper;
import team.kas.anime.pojo.*;
import team.kas.anime.service.VideoService;
import team.kas.anime.util.UpUtils;
import team.kas.anime.util.VideoUtil;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FanMapper fanMapper;
    @Autowired
    private CollectionMapper collectionMapper;


    @Override
    public Integer getCount() {
        return videoMapper.getCount();
    }

    @Override
    public List<Video> getAllVideos(Integer page, Integer limit) {
        return videoMapper.getAllVideos(page,limit);
    }

    @Override
    public Result del(String id) {

        Result result = new Result();
        Video video = videoMapper.selectByPrimaryKey(id);
        if(video != null){
            videoMapper.deleteByPrimaryKey(id);
            result.setMsg("删除成功！");
            return result;
        }else{
            result.setCode(500);
            result.setMsg("系统繁忙，请稍后重试！");
            return result;
        }
    }

    @Override
    public Result update(String id, String value, String name) {
        Result result = new Result();
        Video video = videoMapper.selectByPrimaryKey(id);
        if(video != null){
            videoMapper.update(id,value,name);
            return result;
        }else {
            result.setCode(500);
            result.setMsg("系统繁忙，请稍后重试！");
            return result;
        }
    }

    @Override
    @Transactional
    public Result delVideos(String[] ids) {
        Result result = new Result();
        try {
            for (int i = 0; i < ids.length ; i++) {
                videoMapper.deleteByPrimaryKey(ids[i]);
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMsg("系统繁忙，请稍后重试！");
            result.setCode(500);
            return result;
        }
    }

    @Override
    public Result upFile(MultipartFile file, HttpServletRequest request, String type) {
        Result result = new Result();
        try {
            UpUtils.upfile(file,request,type);
            String fileName = file.getOriginalFilename();
            result.setMsg(fileName);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("上传失败，请重试！");
            return result;
        }
    }

    @Override
    public Result addVideo(Video video, HttpServletRequest request) {
        Result result = new Result();
        String id = UUID.randomUUID().toString();
        User user = (User)request.getSession().getAttribute("user");
        String uId = "";
        if(user != null){
            uId = user.getId();
        }
        try {
            MultimediaInfo info = VideoUtil.video(request,video.getVideoPath());
            long duration = info.getDuration();
            Float videoSeconds = Float.valueOf(duration/1000);
            String videoPath = "/video/adminVideo/" + video.getVideoPath();
            String coverPath = "/img/videoImg/" + video.getCoverPath();
            String videoDesc = video.getRemark();
            Video newVideo = new Video(id,uId,video.getVideoDesc(),videoPath,videoSeconds,coverPath,0l,1,0l,0l,new Date(),videoDesc);
            videoMapper.insert(newVideo);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("添加失败！");
            return result;
        }
    }

    @Override
    public Result searchName(String value, Integer page, Integer limit) {
        Result result = new Result();
        page = (page-1)*limit;
        List<Video> videos = videoMapper.selectByName(value,page,limit);
        List<Video> videoCounts = videoMapper.selectByName(value,null,null);
        result.setCount(videoCounts.size());
        result.setData(videos);
        return result;
    }

    @Override
    public Result onload(HttpServletRequest  request) {
        Result result=new Result();
        String string="time";
        List<Video> videoList=videoMapper.selectByCountsUp(string);
        /**
         * 填充videoList，防止当videoList[i]为空时session为空，页面加载不成功
         */
        Video video=getVideo();
        result.setMsg("视频加载完成");
        for (int i=videoList.size();i<8;i++)
        {
            videoList.add(i,video);
        }
        request.getSession().setAttribute("video0",videoList.get(0));
        request.getSession().setAttribute("video1",videoList.get(1));
        request.getSession().setAttribute("video2",videoList.get(2));
        request.getSession().setAttribute("video3",videoList.get(3));
        request.getSession().setAttribute("video4",videoList.get(4));
        request.getSession().setAttribute("video5",videoList.get(5));
        request.getSession().setAttribute("video6",videoList.get(6));
        request.getSession().setAttribute("video7",videoList.get(7));
        return result;
    }

    @Override
    public Result video(HttpServletRequest request, String id) {
        Result result=new Result();
        Integer i = Integer.parseInt(id);
        Video video=videoMapper.selectByNum(i-1,1);
        Video video2=videoMapper.selectByNumber(i-1,1);
        if (video!=null)
        {
            User user=userMapper.selectByNickName(video.getUid());
            try {
                String time=stampToDate(video).toString();
                request.getSession().setAttribute("time",time);
                request.getSession().setAttribute("video",video);
                request.getSession().setAttribute("videoUser",user);
                //点击增加播放量
                Video video1=video2;
                video1.setUid(video2.getUid());
                video1.setPlayCounts(video.getPlayCounts()+1);
                videoMapper.updateByPrimaryKey(video1);
                return result;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                result.setCode(500);
                result.setMsg("error");
                return result;
            }
        }
        else
        {
            result.setCode(500);
            result.setMsg("error");
            return result;
        }
    }

    @Override
    public Result likeVideo(HttpServletRequest request) {
        Result result=new Result();
        String string="like";
        List<Video> videoList=videoMapper.selectByCountsUp(string);
        Video video=getVideo();
        for (int i=videoList.size();i<4;i++)
        {
            videoList.add(i,video);
        }
        request.getSession().setAttribute("likeVideo0",videoList.get(0));
        request.getSession().setAttribute("likeVideo1",videoList.get(1));
        request.getSession().setAttribute("likeVideo2",videoList.get(2));
        request.getSession().setAttribute("likeVideo3",videoList.get(3));
        return result;
    }

    @Override
    public Result fans(HttpServletRequest request,String nickname,String id) {
        Result result=new Result();
        Integer i = Integer.parseInt(id);
        Video video=videoMapper.selectByNumber(i-1,1);//通过视频排序，获取视频上传用户id
        User user=userMapper.selectByNickName(nickname);//通过当前用户昵称获取用户id
        try {
            Fan fan=fanMapper.selectByFanid(user.getId(),video.getUid());
            if (fan!=null)
            {
                request.getSession().setAttribute("fanOrFollow",1);
                Collections collections=collectionMapper.selectById(video.getId(),user.getId());
                if (collections!=null)
                {
                    request.getSession().setAttribute("coll",1);
                }
                else
                {
                    request.getSession().setAttribute("coll",0);
                }
                return result;
            }
            else
            {
                request.getSession().setAttribute("fanOrFollow",0);
                return result;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            request.getSession().setAttribute("fanOrFollow",0);
            result.setCode(500);
            result.setMsg("加载失败");
            return result;
        }
    }

    @Override
    public Result follow(HttpServletRequest request, String userid, String videoUserid,Integer follow) {
        Result result=new Result();
        if(follow==1)
        {
            try {
                fanMapper.deleteById(userid,videoUserid);
                return result;
            }catch (Exception e)
            {
                result.setCode(500);
                result.setMsg("error");
                return result;
            }
        }
        else
        {
            Fan fan=new Fan();
            String id= UUID.randomUUID().toString();
            fan.setId(id);
            fan.setFanId(userid);
            fan.setUid(videoUserid);
            try {
                Fan fan1=fanMapper.selectByFanid(userid,videoUserid);
                if (fan1!=null)
                {
                    fanMapper.insert(fan);
                    return result;
                }
                else
                {
                    result.setCode(500);
                    return result;
                }

            }catch (Exception e)
            {
                result.setCode(500);
                result.setMsg("error");
                return result;
            }
        }
    }

    @Override
    public Result like(String videoLike,Integer like,String videoId) {
        Result result=new Result();
        Integer i=Integer.parseInt(videoLike);
        if (like==1)
        {
            try {
                videoMapper.updateByLike(i+1,videoId);
                return result;
            }
            catch (Exception e)
            {
                result.setCode(500);
                result.setMsg("error");
                return result;
            }
        }
        else
        {
            try {
                videoMapper.updateByLike(i-1,videoId);
                return result;
            }catch (Exception e)
            {
                result.setCode(500);
                result.setMsg("error");
                return result;
            }
        }
    }

    @Override
    public Result collection(String videoId, String userId) {
        Result result=new Result();
        Collections collections0=collectionMapper.selectById(videoId,userId);
        if (collections0==null)
        {
            try {
                Collections collections=new Collections();
                String id= UUID.randomUUID().toString();
                collections.setId(id);
                collections.setUid(userId);
                collections.setVid(videoId);
                collectionMapper.insert(collections);
                return result;
            }catch (Exception e)
            {
                result.setCode(500);
                result.setMsg("eroor");
                return result;
            }
        }
        else
        {
            result.setCode(300);
            result.setMsg("你以收藏过该视频");
            return result;
        }
    }
    //创建默认视频对象4
    private Video getVideo()
    {
        Video video=new Video();
        video.setId("error");
        video.setCoverPath("/img/indexImg/cont/main_pic.jpg");
        video.setVideoDesc("视频名称");
        video.setVideoSeconds(999.0f);
        video.setUid("用户");
        video.setPlayCounts(9999999l);
        return video;
    }
    /*
     * 将时间戳转换为时间
     */
    public static java.sql.Date stampToDate(Video video) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化规则
        Date date = video.getCreateTime();//获得要处理的时间 Date型
        String strDate= sdf.format(date);//格式化成yyyy-MM-dd格式的时间字符串
        Date newDate =sdf.parse(strDate);//将字符串转换为时间格式
        java.sql.Date resultDate = new java.sql.Date(newDate.getTime());//最后转换成 java.sql.Date类型数据就可以了，此处最开始数据类型为Date。
        return resultDate;
    }
}
